import React, { PureComponent } from 'react';
import { connect } from 'dva';
import Link from 'umi/link';
import * as Utils from '@/utils/utils';
import * as UUIDS from '@/utils/uuid';
import AccountJS from '@/utils/account';
import Enumerable from 'linq';

import {
  Row,
  Col,
  Card,
  Table,
  Form,
  Button,
  Input,
  Drawer,
  Select,
  DatePicker,
  Dropdown,
  Tooltip,
  Progress,
  Menu,
} from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import LockInvForm from '@/components/LockInvForm';
import ReceiveForm from '@/components/ReceiveForm';
import RelationerDetailDrawer from './drawer.js';

import styles from './styles.less';

const { Option } = Select;
const { Item: FormItem } = Form;
const { Item: MenuItem } = Menu;

const { RangePicker, MonthPicker } = DatePicker;

const ModelName = 'receiveGroup';

@connect(({ receiveGroup, loading, faPiaoState, tiDanState, currency, user }) => ({
  loading: loading.models[ModelName],
  model: receiveGroup,
  fps: faPiaoState.list,
  tds: tiDanState.list,
  curs: currency.list,
  cUser: user.currentUser,
}))
@Form.create()
class Comp extends PureComponent {
  invType = 0;

  state = {
    recFormVisible: false,
    detailVisible: false,
    currentItem: {},

    startMonth: null,
    endMonth: null,
  };

  componentDidMount() {
    this.doQuery();
  }

  doQuery(cond) {
    const { dispatch, model, cUser } = this.props;
    let payload = {
      ...model.qc,
      userId: cUser.id,
    };
    if (cond) {
      payload = {
        ...payload,
        ...cond,
      };
    }
    dispatch({
      type: `${ModelName}/get`,
      payload: payload,
    });
  }

  handlePageChange = (number, size) => {
    const cond = {
      pageSize: size,
      pageNumber: number,
    };
    this.doQuery(cond);
  };



  handleSearch = e => {
    e.preventDefault();

    const { form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const payload = {
        ...fieldsValue,
        dateStart:
          fieldsValue.yearMonth && Array.isArray(fieldsValue.yearMonth)
            ? Utils.getChineseDate(fieldsValue.yearMonth[0])
            : null,
        dateEnd:
          fieldsValue.yearMonth && Array.isArray(fieldsValue.yearMonth)
            ? Utils.getChineseDate(fieldsValue.yearMonth[1])
            : null,
      };
      delete payload.yearMonth;
      console.log("YEAR MONTH:", payload)
      this.doQuery(payload);
    });
  };

  handleFormReset = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.resetFields();
    dispatch({
      type: `${ModelName}/reSetQC`,
    });
  };

  handleRelationerClick = (record) => {
    this.setState({
      currentItem: record,
      detailVisible: true
    });
  }

  queryForm = () => {
    const {
      form: { getFieldDecorator },
      model,
    } = this.props;

    const { curs } = this.props;
    const { qc } = model;

    const colSpanLayout = {
      xs: 24,
      md: 12,
      lg: 5,
    };

    const colSpanLayout_Last = {
      xs: 24,
      md: 12,
      lg: 3,
    };

    const formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
        lg: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 },
        lg: { span: 17 },
      },
    };

    return (
      <Form onSubmit={this.handleSearch}>
        <Row gutter={1} className={styles.dataRow}>
          <Col {...colSpanLayout}>
            <FormItem label="关键字" {...formLayout}>
              {getFieldDecorator('keyword', {
                initialValue: qc.keyword,
              })(<Input placeholder="单位名称、单号" />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="账单类型" {...formLayout}>
              {getFieldDecorator('invType', {
                initialValue: qc.invType,
              })(
                <Select>
                  {
                    [{ id: 1, objectName: '应收' }, { id: 2, objectName: '应付' }].map(item =>
                      <Option key={item.id} value={item.id} >{item.objectName}</Option>)
                  }
                </Select>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="年月" {...formLayout}>
              {getFieldDecorator('yearMonth', {
                // initialValue: qc.dateStart && qc.dateEnd ? [moment(qc.dateStart), moment(qc.dateEnd)] : null,
              })(
                <RangePicker format="YYYY-MM" showPanels={['month', 'month']} />
              )}
            </FormItem>
          </Col>
          {/* <Col {...colSpanLayout}>
            <FormItem label="起始年月" {...formLayout}>
              {getFieldDecorator('startYearMonth', {
                initialValue:
                  qc.startYear && qc.startYear > 0 && qc.startMonth && qc.startMonth > 0
                    ? moment(`${qc.startYear}-${qc.startMonth}`)
                    : null,
              })(<MonthPicker style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="终止年月" {...formLayout}>
              {getFieldDecorator('endYearMonth', {
                initialValue:
                  qc.endYear && qc.endYear > 0 && qc.endMonth && qc.endMonth > 0
                    ? moment(`${qc.endYear}-${qc.endMonth}`)
                    : null,
              })(<MonthPicker style={{ width: '100%' }} />)}
            </FormItem>
          </Col> */}
          <Col {...colSpanLayout}>
            <FormItem label="币种" {...formLayout}>
              {getFieldDecorator('currencyId', {
                initialValue: qc.currencyId,
              })(
                <Select placeholder="请选择">
                  {[{ id: 0, objectName: '全部' }].concat(curs).map(p => (
                    <Option value={p.id} key={p.id}>
                      {p.objectName}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout_Last}>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  render() {
    const { model, loading } = this.props;
    const { data, qc } = model;

    const footerContent = () => {
      const groupSum = Enumerable.from(data.dataList)
        .groupBy('$.currencyName', null, (key, g) => {
          const result = {
            currencyName: key,
            amount: g.sum('$.amount'),
            receive: g.sum('$.receive'),
          };
          return result;
        })
        .toArray();

      return groupSum && (
        <div className={styles.relFooter}>
          {groupSum.map(item => (
            <p key={item.currencyName}>
              <span className={styles.currencyName}>{item.currencyName}</span>
              <span className={styles.total}>总额:{AccountJS.format(item.amount, 2)}</span>
              <span className={styles.total}>已结:{AccountJS.format(item.receive, 2)}</span>
              <span className={styles.total}>差额:{AccountJS.format(Math.abs(item.receive - item.amount), 2)}</span>
            </p>
          ))}
        </div>
      );
    };


    const listTable = () => {
      const columns = [
        {
          title: '#',
          dataIndex: 'ReNo',
          render: (text, record, index) => (
            <span> {index + 1} </span>
          ),
        },
        {
          title: '名称',
          dataIndex: 'relationerName',
          render: (text, record) => <a onClick={() => this.handleRelationerClick(record)} >{text}</a>,
          sorter: (a, b) => a.relationerName.length - b.relationerName.length,
        },
        {
          title: '金额',
          dataIndex: 'amount',
          align: 'right',
          sorter: (a, b) => a.amount - b.amount,
          render: (text, record) => <span>{AccountJS.format(record.amount, 2)}</span>,

        },
        {
          title: '结清',
          dataIndex: 'receive',
          align: 'right',
          sorter: (a, b) => a.receive - b.receive,
          render: (text, record) => <span>{AccountJS.format(record.receive, 2)}</span>,
        },
        {
          title: '欠款',
          dataIndex: 'receiveLeft',
          align: 'right',
          render: (text, record) => AccountJS.format(record.amount - record.receive, 2)
        },
        {
          title: '结清比',
          dataIndex: 'receiveRate',
          render: (text, record) => {
            return <Progress percent={(record.receive / record.amount) * 100} strokeWidth={10} style={{ width: 150 }} format={percent => AccountJS.format(percent, 1) + '%'} />
          },
        },
        {
          title: '币种',
          dataIndex: 'currencyName',
        },
      ];

      return (<Table
        rowKey={record => `${record.relationerId + '-' + record.currencyId}`}
        size="small"
        style={{ marginTop: 12 }}
        loading={loading}
        dataSource={data.dataList}
        columns={columns}
        pagination={false}
        footer={() => footerContent()}
      />
      )
    }

    return (
      <PageHeaderWrapper>
        <div className={styles.tableListForm}>{this.queryForm()}</div>
        <Card bordered={false}>
          {listTable()}
        </Card>
        <RelationerDetailDrawer
          closable={false}
          onClose={() => this.setState({
            detailVisible: false,
          })}
          qc={qc}
          visible={this.state.detailVisible}
          currentItem={this.state.currentItem}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Comp;
